import { useRequest } from '@umijs/max';
import { message } from 'antd';
import { history } from '@umijs/max';
import { clearToken } from '@/utils/authInterceptor';

/**
 * 统一的API请求Hook
 * 提供统一的错误处理、loading状态管理和请求拦截
 */

interface UseApiOptions {
  manual?: boolean;
  loadingDelay?: number;
  onSuccess?: (data: any, params: any[]) => void;
  onError?: (error: any, params: any[]) => void;
  onFinally?: (params: any[], data?: any, error?: any) => void;
  refreshDeps?: any[];
  ready?: boolean;
  defaultParams?: any[];
  formatResult?: (response: any) => any;
  throwOnError?: boolean;
}

/**
 * 统一的错误处理函数
 */
const handleApiError = (error: any) => {
  console.error('API请求错误:', error);
  
  if (error?.response) {
    const { status, data } = error.response;
    switch (status) {
      case 401:
        clearToken();
        message.error('登录已过期，请重新登录');
        history.replace('/login');
        break;
      case 403:
        message.error('权限不足，您没有权限执行此操作');
        break;
      case 404:
        message.error('请求的资源不存在');
        break;
      case 500:
        message.error('服务器内部错误');
        break;
      default:
        const errorMessage = data?.message || error.message || '网络请求失败';
        message.error(errorMessage);
        break;
    }
  } else if (error?.request) {
    message.error('网络连接失败，请检查网络');
  } else {
    const errorMessage = error?.message || '请求失败';
    message.error(errorMessage);
  }
};

/**
 * 统一的响应处理函数
 */
const handleApiResponse = (response: any) => {
  if (response && response.code !== undefined) {
    switch (response.code) {
      case 200:
        // 接口成功，返回数据
        return response.data || response;
      case 401:
        clearToken();
        message.error('登录已过期，请重新登录');
        history.replace('/login');
        throw new Error('登录已过期');
      case 403:
        message.error('权限不足，您没有权限执行此操作');
        throw new Error('权限不足');
      default:
        const errorMessage = response.message || '请求失败';
        message.error(errorMessage);
        throw new Error(errorMessage);
    }
  }
  
  return response;
};

/**
 * 统一的API请求Hook
 * @param apiFunction API函数
 * @param options 配置选项
 * @returns useRequest的返回值
 */
export const useApi = <T = any, P extends any[] = any[]>(
  apiFunction: (...args: P) => Promise<T>,
  options: UseApiOptions = {}
) => {
  const {
    manual = false,
    loadingDelay = 300,
    onSuccess,
    onError,
    onFinally,
    refreshDeps,
    ready = true,
    defaultParams,
    formatResult,
    throwOnError = false,
    ...restOptions
  } = options;

  return useRequest(apiFunction, {
    manual,
    loadingDelay,
    ready,
    refreshDeps,
    defaultParams,
    formatResult: (response: any) => {
      try {
        const processedResponse = handleApiResponse(response);
        return formatResult ? formatResult(processedResponse) : processedResponse;
      } catch (error) {
        if (throwOnError) {
          throw error;
        }
        return null;
      }
    },
    onSuccess: (data, params) => {
      onSuccess?.(data, params);
    },
    onError: (error, params) => {
      if (!throwOnError) {
        handleApiError(error);
      }
      onError?.(error, params);
    },
    onFinally,
    ...restOptions,
  });
};

/**
 * 用于表格数据的API请求Hook
 * 自动处理分页和搜索参数
 */
export const useTableApi = <T = any>(
  apiFunction: (params: any) => Promise<T>,
  options: UseApiOptions = {}
) => {
  return useApi(apiFunction, {
    manual: true,
    formatResult: (response: any) => {
      if (response && response.data) {
        return {
          data: response.data.list || response.data,
          success: response.code === 200,
          total: response.data.pagination?.total || response.data.length || 0,
        };
      }
      return {
        data: [],
        success: false,
        total: 0,
      };
    },
    ...options,
  });
};

/**
 * 用于删除操作的API请求Hook
 * 自动显示确认对话框和成功消息
 */
export const useDeleteApi = <T = any>(
  apiFunction: (...args: any[]) => Promise<T>,
  options: UseApiOptions & {
    successMessage?: string;
    confirmTitle?: string;
    confirmContent?: string;
  } = {}
) => {
  const {
    successMessage = '删除成功',
    confirmTitle = '确认删除',
    confirmContent = '确定要删除吗？此操作不可恢复。',
    onSuccess,
    ...restOptions
  } = options;

  return useApi(apiFunction, {
    manual: true,
    onSuccess: (data, params) => {
      message.success(successMessage);
      onSuccess?.(data, params);
    },
    ...restOptions,
  });
};

/**
 * 用于导出操作的API请求Hook
 * 自动处理文件下载
 */
export const useExportApi = <T = any>(
  apiFunction: (...args: any[]) => Promise<T>,
  options: UseApiOptions & {
    filename?: string;
    successMessage?: string;
  } = {}
) => {
  const {
    filename = 'export',
    successMessage = '导出成功',
    onSuccess,
    ...restOptions
  } = options;

  return useApi(apiFunction, {
    manual: true,
    onSuccess: (blob, params) => {
      if (blob instanceof Blob) {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${filename}_${new Date().toISOString().split('T')[0]}.xlsx`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        message.success(successMessage);
      }
      onSuccess?.(blob, params);
    },
    ...restOptions,
  });
};

/**
 * 用于批量操作的API请求Hook
 */
export const useBatchApi = <T = any>(
  apiFunction: (...args: any[]) => Promise<T>,
  options: UseApiOptions & {
    successMessage?: string;
  } = {}
) => {
  const {
    successMessage = '批量操作成功',
    onSuccess,
    ...restOptions
  } = options;

  return useApi(apiFunction, {
    manual: true,
    onSuccess: (data, params) => {
      message.success(successMessage);
      onSuccess?.(data, params);
    },
    ...restOptions,
  });
};
